package org.altervista.cp.thinjdbc;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;

import org.altervista.cp.thinjdbc.wrappers.Connection;

public class JTASession extends Session {

	public JTASession(String dsJNDIName, String utJNDIName)
			throws NamingException {
		this(dsJNDIName, (UserTransaction) new InitialContext()
				.lookup(utJNDIName));
	}

	public JTASession(Connection cw, String utJNDIName) throws NamingException {
		this(cw, (UserTransaction) new InitialContext().lookup(utJNDIName));
	}

	public JTASession(String dsJNDIName, UserTransaction ut)
			throws NamingException {
		super(dsJNDIName);
		super.setCommitTransactionOnClose(true);
		_ut = ut;
	}

	public JTASession(Connection cw, UserTransaction ut) {
		super(cw);
		_ut = ut;
	}

	public void begin() {
		if (_ut == null) {
			super.begin();
		} else {
			try {
				_ut.begin();
			} catch (Throwable t) {
				throw new IllegalStateException(t);
			}
		}
	}

	public void commit() {
		if (_ut == null) {
			super.commit();
		} else {
			try {
				_ut.commit();
			} catch (Throwable t) {
				rollback(t);
			}
		}
	}

	public void rollback() {
		if (_ut == null) {
			super.rollback();
		} else {
			rollback(null);
		}
	}

	public void setCommitTransactionOnClose(boolean commitTransactionOnClose) {
		if (_ut == null) {
			super.setCommitTransactionOnClose(commitTransactionOnClose);
		} else {
			throw new UnsupportedOperationException(
					"JTASesssions MUST be able to commit transactions on close");
		}
	}

	public void rollback(Throwable t) {
		try {
			_ut.rollback();
		} catch (Throwable tt) {
			throw new IllegalStateException(t);
		}
	}

	private UserTransaction _ut;
}
